package com.itheima.easy.face.impl;

import com.itheima.easy.adapter.AppPayAdapter;
import com.itheima.easy.constant.TradingCacheConstant;
import com.itheima.easy.enums.TradingEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.face.AppPayFace;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.vo.TradingVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName AppPayFaceImpl.java
 * @Description 手机网页支付Face接口实现
 */
@Slf4j
@Component
public class AppPayFaceImpl implements AppPayFace {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    AppPayAdapter appPayAdapter;

    /***
     * @description 生成支付会话秘钥，渲染后自动跳转支付宝或者微信引导用户完成支付
     * @param tradingVo 订单单
     * @return  TradingVo对象中的placeOrderJson：支付会话秘钥
     */
    public TradingVo appTrading(TradingVo tradingVo) {
        //防止并发：使用订单号，对本次交易加锁
        String key = TradingCacheConstant.CREATE_PAY + tradingVo.getProductOrderNo();
        RLock lock = redissonClient.getFairLock(key);
        try {
            if (lock.tryLock(TradingCacheConstant.REDIS_WAIT_TIME, TimeUnit.SECONDS)){
                return appPayAdapter.appTrading(tradingVo);
            }else {
                throw new ProjectException(TradingEnum.PAYING_TRADING_FAIL);
            }
        } catch (Exception e) {
            log.error("统一收单线下交易预创建异常:{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradingEnum.TRYLOCK_TRADING_FAIL);
        }finally {
            //释放锁
            lock.unlock();
        }
    }
}
